var Consultant = {
    id: "ConsultantTable",
    seItem: null,
    table: null,
    layerIndex: -1
};
var parseParam = function (param) {
    var paramStr = "";
    $.each(param, function (i) {
        paramStr += '&' + getSingleData(param, i);
    });
    return paramStr.substr(1);
};
var getSingleData = function (param, key) {
    return key + "=" + param[key];
};

function _cellStyles(value, row, index) {
    if (row.diagnosisStatus === "已看诊") {
        return {css: {"background-color": "#fff1d5", "overflow": "hidden", "white-space": "nowrap", "text-overflow": "ellipsis"}}
    } else {
        return {css: {"overflow": "hidden", "white-space": "nowrap", "text-overflow": "ellipsis"}}
    }
}

Consultant.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'customerSexHead ', visible: false, align: 'center', valign: 'middle'},
        {title: 'checkStatus', field: 'checkStatus', visible: false, align: 'center', valign: 'middle'},
        {title: 'reservationsId', field: 'reservationsId', visible: false, align: 'center', valign: 'middle'},
        {title: 'orthodonticsStatus', field: 'orthodonticsStatus', visible: false, align: 'center', valign: 'middle'},
        {
            title: '病历号', field: 'medicalRecordNumber', align: 'center', valign: 'middle', sortable: true, width: 120,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '客户姓名', field: 'customerName', align: 'center', valign: 'middle', sortable: true, width: 120,
            formatter: function (value, row, index) {
                if (row.orthodonticsStatus > 0) {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' onclick = 'Consultant.consultantToDetail(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span><img src=\"https://pynnn.oss-cn-hangzhou.aliyuncs.com/ychh001.png\" alt=\"...\" width=\"18px;\"></a>"
                }else {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' onclick = 'Consultant.consultantToDetail(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                }
            },
            cellStyle: function (value, row, index) {
                if (row.diagnosisStatus === "已看诊") {return {css: {"background-color": "#fff1d5"}}} else {return {}}
            }
        },
        {
            title: '电话', field: 'customerPhone', align: 'center', valign: 'middle', sortable: true, width: 140,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '性别', field: 'customerSex', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                return value === 1 ? '男' : value === 2 ? '女' : '未知';
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '年龄', field: 'customerAge', align: 'center', valign: 'middle', sortable: true, width: 70,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '已交金额', field: 'actualAccountBalance', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if (row.accountArrears > 0) {
                    return "<a href='javascript:;' style='background-color: #fff1d5'>" + (row.actualAccountBalance + row.moneyBalance+ parseFloat(row.orthodonticsStatus)) + "</a>"
                } else {
                    return "<a href='javascript:;'>" + (row.actualAccountBalance + row.moneyBalance+ parseFloat(row.orthodonticsStatus)) + "</a>"
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '欠费', field: 'accountarrears', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                if (row.checkStatus == 1) {
                    if (value > 0) {
                        return '<span style="color: red;" title="' + value + '">' + value + '<span style="color: white;background: #FF7E00;padding: 0 2px;border-radius: 50%;margin-left: 4px;">查</span></span>'
                    } else {
                        return '<span title="' + value + '">' + value + '<span style="color: white;background: #FF7E00;padding: 0 2px;border-radius: 50%;margin-left: 4px;">查</span></span>'
                    }
                } else {
                    if (value > 0) {
                        return "<span style='color: red;'>" + value + "</span>"
                    } else {
                        return "<span>" + value + "</span>"
                    }
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '客户状态', field: 'customerStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '看诊状态', field: 'diagnosisStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if (value === "已看诊") {
                    return "<span style='color: green;'>" + value + "</span>"
                } else {
                    return "<span style='color: red;'>" + value + "</span>"
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '开单状态', field: 'dealStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if(value !== "未开单" && value !== "已开单"){
                    return "<span style='color: green;'>已结账</span>"
                }else {
                    return value;
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '成交状态', field: 'isdealStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if (value === "已成交") {
                    return "<span style='color: green;'>" + value + "</span>"
                } else {
                    return "未成交";
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '科室', field: 'treatmentUnit', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return "<span style='color: red;'>" + value + "</span>"
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: 'TC', field: 'fieldTc', align: 'center', valign: 'middle', sortable: true, width: 100,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '跟踪状态', field: 'followStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '消费状态', field: 'consumptionStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '无龋齿儿童', field: 'childrenCard', align: 'center', valign: 'middle', sortable: true, width: 110,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '回访时间', field: 'appointmentTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                if (value != null && value !== "") {
                    return value.substring(0, 19);
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '初诊时间', field: 'firstVisitDate', align: 'center', valign: 'middle', sortable: true, width: 110,
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        },
        {
            title: '到店时间', field: 'arrivalTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                if (value != null && value !== "") {
                    return value.substring(0, 19);
                }
            },
            cellStyle: function (value, row, index) {
                return _cellStyles(value, row, index);
            }
        }
    ];
    return columns;
};

Consultant.consultantToDetail = function (id) {
    var index = layer.open({
        type: 2,
        title: '&nbsp',
        area: ['100%', '100%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/consultantDetails/consultantToDetailByTab/' + id + '/0/0'
    });
    this.layerIndex = index;
};

Consultant.customerReconsulting = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '患者重咨',
            area: ['40%', '50%'], //宽高
            fix: true, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/customer/to_reconsultingTc/' + Consultant.seItem.reservationsId
        });
        this.layerIndex = index;
    }
};

Consultant.choiceCustomerStatus = function (id) {
    var index = layer.open({
        type: 2,
        title: '选择客户状态',
        area: ['60%', '60%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/customer/to_choice_status/' + id
    });
    this.layerIndex = index;
};

Consultant.opendealStatus = function (id) {
    $.ajax({
        url: Feng.ctxPath + "/reservations/getTotleMoneys",
        type: "post",
        data: {
            "id": id
        },
        success: function (data) {
            alert("成交金额：" + data + "元");
        },
        error: function (data) {
            alert('没有权限，请联系系统管理员!');
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        }
    });
};

Consultant.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        Consultant.seItem = selected[0];
        return true;
    }
};

Consultant.updateDiagnosisDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '看诊详情',
            area: ['90%', '90%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/consultant/consultant_update/' + Consultant.seItem.id
        });
        this.layerIndex = index;
    }
};

Consultant.delete = function () {
    if (this.check()) {
        var ajax = new $ax(Feng.ctxPath + "/consultant/delete/" + this.seItem.id, function (data) {
            Feng.success("删除成功!");
            Consultant.table.refresh();
        }, function (data) {
            alert("没有权限，请联系系统管理员！");
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });
        ajax.start();
    }
};

Consultant.search = function () {
    document.getElementById("fieldTcValue").value = $("#fieldTc").val();
    Consultant.table.refresh({query: Consultant.formParams()});
    Consultant.total();
};

Consultant.consultantExport = function () {
    var param = parseParam(Consultant.formParams());
    location.href = Feng.ctxPath + '/consultant/consultantExport?' + param;
}

Consultant.resetSearch = function () {
    $("#followStatus").selectpicker('deselectAll');
    $("#dealStatus").val("");
    $("#consumptionStatus").selectpicker('deselectAll');
    parent.$("#doctorTcInputPublic").val("");
    $("#fieldTcValue").val("");
    $("#startArrivalTime").val("");
    $("#endArrivalTime").val("");
    $("#diagnosisStatus").val("");
    $("#treatmentUnit").val("");
    $("#firstReturnSettings").val("");
    $("#customerStatusValue").val("");
    $(".timeBox > div button").removeClass('actionClick');
    Consultant.search();
};

Consultant.formParams = function () {
    var queryData = {};
    queryData['reach'] = parent.$("#doctorTcInputPublic").val().trim();
    queryData['abbreviation'] = $("#abbreviation", parent.document).val();
    queryData['startArrivalTime'] = $("#startArrivalTime").val();
    queryData['endArrivalTime'] = $("#endArrivalTime").val();
    queryData['fieldTc'] = document.getElementById("fieldTcValue").value;
    queryData['treatmentUnit'] = $("#treatmentUnit").val();
    queryData['followStatus'] = multipleSelection($('#followStatus').val());
    queryData['dealStatus'] = $("#dealStatus").val();
    queryData['diagnosisStatus'] = $("#diagnosisStatus").val();
    queryData['firstReturnSettings'] = $("#firstReturnSettings").val();
    queryData['consumptionStatus'] = multipleSelection($('#consumptionStatus').val());
    queryData['customerStatus'] = $("#customerStatusValue").val();
    return queryData;
};

Consultant.today = function () {// 今日
    $("#startArrivalTime").val(setDateTime(new Date(), 0) + " " + "00:00:00");
    $("#endArrivalTime").val(setDateTime(new Date(), 0) + " " + "23:59:59");
    $(".timeBox > div button").eq(0).addClass('actionClick').siblings().removeClass('actionClick');
    Consultant.search();
};

Consultant.yesterday = function () {// 昨日
    $("#startArrivalTime").val(setDateTime(new Date(), 1) + " " + "00:00:00");
    $("#endArrivalTime").val(setDateTime(new Date(), 1) + " " + "23:59:59");
    $(".timeBox > div button").eq(1).addClass('actionClick').siblings().removeClass('actionClick');
    Consultant.search();
};

Consultant.thisWeek = function () { // 本周
    var date = new Date();
    var currentWeek = date.getDay();
    var stepSunDay = -currentWeek + 1;
    if (currentWeek == 0) {
        stepSunDay = -7;
    }
    var stepMonday = 7 - currentWeek;
    var time = date.getTime();
    var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
    var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
    $("#startArrivalTime").val(setDateTime(monday, 0) + " " + "00:00:00");
    $("#endArrivalTime").val(setDateTime(sunday, 0) + " " + "23:59:59");
    $(".timeBox > div button").eq(2).addClass('actionClick').siblings().removeClass('actionClick');
    Consultant.search();
};

Consultant.total = function () { // 统计总人数
    var param1 = $("#startArrivalTime").val();  //开始到店时间
    var param2 = $("#endArrivalTime").val();   //结束到店时间
    var param3 = multipleSelection($('#followStatus').val());
    var param4 = multipleSelection($('#consumptionStatus').val());
    var param5 = document.getElementById("fieldTcValue").value;
    var param6 = parent.$("#doctorTcInputPublic").val();
    var param7 = $("#dealStatus").val();   //开单状态
    var param8 = $("#diagnosisStatus").val();
    var param9 = $("#treatmentUnit").val();
    $.ajax({ //获取跟踪人数
        type: "GET",
        url: Feng.ctxPath + "/consultantTwo/total",
        data: {
            param1: param1, param2: param2, param3: param3, param4: param4, param5: param5
            , param6: param6, param7: param7, param8: param8, param9: param9
        },
        dataType: "json",
        success: function (data) {
            $("#total").html(data[0].countNum);//总人数
            $("#first").html(data[1].countNum);//新客首次
            $("#two").html(data[2].countNum);//新客二次
            $("#further").html(data[3].countNum);//复诊
            $("#old").html(data[4].countNum);//老客
            $("#fzsum").html(data[5].countNum);//复诊人次
            $("#wszsum").html(data[6].countNum);//未设置回访
        }
    });
};

Consultant.totalNumber = function (ojb) { //总人数数据详情
    document.getElementById("customerStatusValue").value = ojb;
    var queryData = {};
    queryData['startArrivalTime'] = $("#startArrivalTime").val();//开始到店时间
    queryData['endArrivalTime'] = $("#endArrivalTime").val();//结束到店时间
    queryData['followStatus'] = multipleSelection($('#followStatus').val());
    queryData['consumptionStatus'] = multipleSelection($('#consumptionStatus').val());
    queryData['dealStatus'] = $("#dealStatus").val();// 开单状态
    queryData['fieldTc'] = document.getElementById("fieldTcValue").value;
    queryData['reach'] = parent.$("#doctorTcInputPublic").val();
    queryData['diagnosisStatus'] = $("#diagnosisStatus").val();
    queryData['treatmentUnit'] = $("#treatmentUnit").val();
    queryData['firstReturnSettings'] = $("#firstReturnSettings").val();
    queryData['customerStatus'] = $("#customerStatusValue").val();
    Consultant.search();
};

$("#doctorTcSearchAll", parent.document).click(function () { //主页搜索
    Consultant.search();
});

function phonePrivileges() {   //隐藏手机号
    var phonePrivileges = parent.$("#phonePrivileges").val();
    if (phonePrivileges == 2) {
        $('#ConsultantTable').bootstrapTable('hideColumn', 'customerPhone');
    }
}

$(function () {
    var defaultColunms = Consultant.initColumn();
    var table = new BSTable(Consultant.id, "/consultant/list", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(Consultant.formParams());
    Consultant.table = table.init();
    checkDate = function () {
        Consultant.search();
    };
    callbackTable = function () {
        Consultant.search();
    };
    $("#totalCount").addClass('actionClick').siblings().removeClass('actionClick');
    $(document).on('click', '#laydate_clear,#laydate_today,#laydate_ok', function () {
        Consultant.search();
    });
    menuNameHideColumn($("#menuName").val(), 'ConsultantTable');
    var seletefieldTc = $('#fieldTcValues').val();
    if (seletefieldTc != "") {
        $("#fieldTc option[value='" + seletefieldTc + "']").attr("selected", "selected");
        $("#fieldTc1 option[value='" + seletefieldTc + "']").attr("selected", "selected");
        if ($('#fieldTc').val() == "") {
            $('#fieldTcUpdate').show();
            $('#fieldTcCanNotUpdate').hide();
        } else {
            $('#fieldTcUpdate').hide();
            $('#fieldTcCanNotUpdate').show();
        }
    }
    Consultant.today();
    phonePrivileges();
});